<template>
    <div>
        <div class="content-header">
            <div class="container">
                <h1>图书管理</h1>
                <!-- <uploadChapterContainer></uploadChapterContainer> -->
            </div>
        </div>

        <div class="content">
            <div class="container">

                <div class="box">

                    <div class="filter-container">
                        <el-form-item>
                            <el-input v-model="pagination.type" placeholder="图书类别" style="width: 200px;"
                                class="filter-item"></el-input>

                            <el-input v-model="pagination.name" placeholder="图书名称" style="width: 200px;"
                                class="filter-item"></el-input>
                            <el-input v-model="pagination.description" placeholder="图书描述" style="width: 200px;"
                                class="filter-item"></el-input>
                            <el-button @click="getAll()" class="dalfBut">查询</el-button>
                            <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                        </el-form-item>
                    </div>

                    <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>

                        <el-table-column type="index" align="center" label="序号"></el-table-column>

                        <el-table-column prop="type" label="图书类别" align="center"></el-table-column>

                        <el-table-column prop="name" label="图书名称" align="center"></el-table-column>

                        <el-table-column prop="description" label="描述" align="center"></el-table-column>

                        <el-table-column label="操作" align="center">

                            <template #default="scope">

                                <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>

                                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>

                                <el-button type="success" size="small" @click="handleReadBook(scope.row)">阅读</el-button>

                            </template>

                        </el-table-column>

                    </el-table>

                    <!--分页组件-->
                    <div class="pagination-container" style="margin-top:20px;">

                        <el-pagination class="pagiantion" @current-change="handleCurrentChange"
                            :current-page="pagination.currentPage" :page-size="pagination.pageSize"
                            layout="total, prev, pager, next, jumper" :total="pagination.total">

                        </el-pagination>

                    </div>

                    <!-- 新增标签弹层 -->

                    <div class="add-form">
                        <el-dialog title="新增图书" v-model="dialogFormVisible">
                            <el-form ref="dataAddForm" v-model="formData" :rules="rules" label-position="right"
                                label-width="100px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="图书类别" prop="type">
                                            <el-input v-model="formData.type" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="图书名称" prop="name">
                                            <el-input v-model="formData.name" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="描述">
                                            <el-input v-model="formData.description" type="textarea"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                            <template #footer>
                                <div class="dialog-footer">
                                    <el-button @click="cancel()">取消</el-button>
                                    <el-button type="primary" @click="handleAdd()">确定</el-button>
                                </div>
                            </template>
                        </el-dialog>
                    </div>

                    <!-- 编辑标签弹层 -->

                    <div class="add-form">

                        <el-dialog title="编辑检查项" v-model="dialogFormVisible4Edit">

                            <el-form ref="dataEditForm" v-model="formData" :rules="rules" label-position="right"
                                label-width="100px">

                                <el-row>

                                    <el-col :span="12">

                                        <el-form-item label="图书类别" prop="type">

                                            <el-input v-model="formData.type" />

                                        </el-form-item>

                                    </el-col>

                                    <el-col :span="12">

                                        <el-form-item label="图书名称" prop="name">

                                            <el-input v-model="formData.name" />

                                        </el-form-item>

                                    </el-col>

                                </el-row>

                                <el-row>

                                    <el-col :span="12">

                                        <el-form-item label="描述">

                                            <el-input v-model="formData.description" type="textarea"></el-input>

                                        </el-form-item>

                                    </el-col>

                                </el-row>

                                <el-row>

                                    <el-col :span="12" :offset="1">
                                        <el-form>
                                            <!-- :before-upload="beforeUpload" -->
                                            <el-upload ref="upload" :http-request="httpRequest" :on-exceed="handleExceed"
                                                :limit="1" 
                                                :file-list="pxyFileList" accept=".zip">

                                                <el-button size="small" type="primary">选择书籍章节</el-button>

                                            </el-upload>


                                            <el-progress v-if="showProgress" :percentage="percentage"></el-progress>
                                        </el-form>
                                    </el-col>
                                </el-row>

                            </el-form>


                            <!-- <template v-slot:dialog-footer>
                                <div class="dialog-footer">
                                    <el-button @click="cancel()">取消</el-button>
                                    <el-button type="primary" @click="handleAdd()">确定</el-button>
                                </div>
                            </template> -->

                            <template #footer>
                                <div class="dialog-footer">
                                    <el-button @click="cancel()">取消</el-button>
                                    <el-button type="primary" @click="handleEdit()">确定</el-button>
                                </div>
                            </template>
                            <!-- <div slot="footer" class="">

                            <el-button @click="cancel()">取消</el-button>

                            <el-button type="primary" @click="handleEdit()">确定</el-button>

                        </div> -->

                        </el-dialog>

                    </div>

                </div>

            </div>
        </div>



    </div>
</template>

<script>
//import { post } from '@/utils/api'
import axios from 'axios';
import gconfig from '@/config/global_config'
//import { get } from '@/utils/api'
import { ElMessage } from 'element-plus';
//import request from '@/utils/request';
import { getAllBooks, getBookById } from "@/apis/book";
import { getTreeView } from "@/apis/chapter";
//import { ref } from 'vue'
import { genFileId } from 'element-plus'
//import uploadChapterContainer from '../Chapter/uploadChapter.vue';


export default {
    name: "bookIndex",
    data() {
        return {
            dataList: [],//当前页要展示的列表数据
            dialogFormVisible: false,//添加表单是否可见
            dialogFormVisible4Edit: false,//编辑表单是否可见
            formData: {},//表单数据
            rules: {//校验规则
                type: [{ required: true, message: '图书类别为必填项', trigger: 'blur' }],
                name: [{ required: true, message: '图书名称为必填项', trigger: 'blur' }]
            },
            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize: 5,//每页显示的记录数
                total: 0,//总记录数
                type: "",
                name: "",
                description: ""
            },
            inputName: '',
            pxyFileList: [],
            showProgress: false,
            percentage: 0
        }

    },

    components: {
        // uploadChapterContainer
    },

    //钩子函数，VUE对象初始化完成后自动执行
    created() {
        this.getAll();
    },

    methods: {
        //列表
        httpRequest(option) {
            console.log(option)
            console.log("====")
            this.pxyFileList.push(option.file)
        },
        /*getAll() {
            // 发送异步请求
            axios.get("/books").then(res => {
                // console.log(res.data);
                this.dataList = res.data.data;
            });

        },*/

        //分页查询
        getAll() {
            getAllBooks(this.pagination).then((res) => {
                if (res) {
                    this.dataList = res.records;
                    this.pagination.currentPage = res.current;
                    this.pagination.pageSize = res.size;
                    this.pagination.total = res.total;
                }
            }).catch((error) => {
                console.log('Failed with reason:', error); // 输出: Failed with reason: error
            });

            //     var condition = "?name=" + this.pagination.name + "&type=" + this.pagination.type + "&description=" + this.pagination.description;
            //     var reqUrl = gconfig.constants.API_ORIGIN + "/books" + "/" + this.pagination.currentPage + "/" + this.pagination.pageSize + condition
            //     request({
            //         url: reqUrl,
            //         method: "get",
            //         data: {},
            // //  needAuthentication: true
            //    });
            // var condition = "?name=" + this.pagination.name + "&type=" + this.pagination.type + "&description=" + this.pagination.description;
            // axios.get(gconfig.constants.API_ORIGIN + "/books" + "/" + this.pagination.currentPage + "/" + this.pagination.pageSize + condition).then((res) => {
            //     console.log(res.data)
            //     this.dataList = res.data.data.records;
            //     this.pagination.currentPage = res.data.data.current;
            //     this.pagination.pageSize = res.data.data.size;
            //     this.pagination.total = res.data.data.total;
            // })
        },
        //切换页码
        handleCurrentChange(currentPage) {
            this.pagination.currentPage = currentPage;
            this.getAll()
        },

        //弹出添加窗口
        handleCreate() {
            this.dialogFormVisible = true;
            this.resetForm();
            this.pxyFileList = []
        },

        //重置表单
        resetForm() {
            this.formData = {};
            this.pxyFileList = []
        },

        //添加
        handleAdd() {
            axios.post(gconfig.constants.API_ORIGIN + "/books", this.formData).then((res) => {
                if (res.data.flag) {
                    // 1.关闭增加弹窗
                    this.dialogFormVisible = false;
                    this.$message.success("添加成功");
                } else {
                    this.$message.error("添加失败");
                }

            }).finally(() => {
                // 2.刷新
                this.getAll();
            })
        },

        //取消
        cancel() {
            this.dialogFormVisible = false;
            this.dialogFormVisible4Edit = false;

            this.$message.info("当前操作取消");
        },
        // 删除
        handleDelete(row) {
            this.$confirm("此操作将永久删除数据，是否继续？", "提示", { type: "info" }).then(() => {
                console.log("success");
                axios.delete(gconfig.constants.API_ORIGIN + "/books/" + row.id).then((res) => {
                    if (res.data.flag) {
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error("数据同步失败，自动刷新");
                    }

                }).finally(() => {
                    // 2.刷新
                    this.getAll();
                })
            }).catch(() => {
                console.log("fail");
                this.$message.info("取消操作");
            })

        },

        handleExceed(files) {
            this.pxyFileList = [];
            //this.$refs['upload'].value.clearFiles();
            const file = files[0];
            file.uid = genFileId(); // 确保已经定义了 genFileId() 函数
            this.pxyFileList = [file]
            this.$refs['upload'].handleStart(file);
        },

        //弹出编辑窗口
        handleUpdate(row) {
            this.pxyFileList = [];
            //this.clearFiles();
            console.log("handlerupdate")
            getBookById(row.id).then((res) => {
                this.dialogFormVisible4Edit = true;
                //console.log(row);
                if (res) {
                    this.formData = res;
                } else {
                    this.$message.error("数据同步失败，自动刷新");
                }
            }).catch((error) => {
                console.log('Failed with reason:', error); // 输出: Failed with reason: error
            }).finally(() => {
                // 2.刷新
                this.getAll();
            });

            // axios.get(gconfig.constants.API_ORIGIN + "/books/" + row.id).then(res => {
            //     this.dialogFormVisible4Edit = true;
            //     //console.log(row);
            //     if (res.data.flag && res.data.data != null) {
            //         this.formData = res.data.data;
            //     } else {
            //         this.$message.error("数据同步失败，自动刷新");
            //     }

            // }).finally(() => {
            //     // 2.刷新
            //     this.getAll();
            // });

        },

        //修改
        async handleEdit() {
            console.log("pxy file list handledit");
            console.log(this.pxyFileList)
            let newFormData = new FormData();
            this.pxyFileList.forEach((x) => {
                console.log(x)
                newFormData.append('file', x)
            });
            newFormData.append('id', this.formData.id);
            newFormData.append('type', this.formData.type);
            newFormData.append('name', this.formData.name);
            newFormData.append('description', this.formData.description);
            // console.log("newFormData");
            // console.log(newFormData)
            //console.log("this.formData", JSON.stringify(newFormData))

            // const response = await fetch(gconfig.constants.API_ORIGIN + '/books/update_book', {
            //     headers: {
            //         "Access-Control-Allow-Origin": "*",
            //         //'Content-Type': 'multipart/form-data'
            //     },
            //     method: 'POST',
            //     body: newFormData,
            //     data: newFormData.file
            // })


            // if (response.ok) {
            //     this.dialogFormVisible4Edit = false;
            //     this.$message.success("更新成功");
            //     const data = response.json();
            //     console.log(data);
            // } else {
            //     this.$message.error("更新失败");
            //     console.log('上传失败');
            // }
            const headers = {
                'Content-Type': 'multipart/form-data',
            };
            axios.post(
                gconfig.constants.API_ORIGIN + "/books/update_book", newFormData, {
                    headers,
                onUploadProgress: (event) => {
                    // 计算上传进度
                    this.showProgress = true;
                    this.percentage = Math.round((event.loaded * 100) / event.total);
                }
            }).then((res) => {
                if (res.data.flag) {
                    // 1.关闭修改弹窗
                    this.dialogFormVisible4Edit = false;
                    this.$message.success("更新成功");
                } else {
                    this.$message.error("更新失败");
                }
                this.showProgress = false;
                this.$refs['upload'].clearFiles()

            }).finally(() => {
                // 2.刷新
                this.getAll();
            })
        },
        // 阅读书籍，跳转到书籍页面
        handleReadBook(row) {
            this.chapterTreeViewCheck(row);
        },

        // handleProgress(event) {
        //     this.percentage = Math.round((event.loaded * 100) / event.total);
        //     console.log('进度:', this.percentage, '%');
        // },

        /**
         * 检查当前跳转的书籍id是否可以阅读
         */
        chapterTreeViewCheck(row) {

            getTreeView(row.id).then((res) => {
                if (res) {
                    this.$router.push({
                        path: '/book/chapter',
                        query: { book_id: row.id },
                    });
                } else {
                    ElMessage.error('当前未配置书籍')
                }
            }).catch((error) => {
                console.log('Failed with reason:', error); // 输出: Failed with reason: error
            });

            // 发送异步请求
            // var url = '/chapter/get_tree_view'
            // try {
            //     // 发送 application/json 类型的 POST 请求
            //     var retData = await get(url, { book_id: row.id }, 'form');
            //     if (retData.data) {
            //        this.$router.push({
            //             path: '/book/chapter',
            //             query: { book_id: row.id },
            //         });
            //     } else {
            //         ElMessage.error('当前未配置书籍')
            //     }

            //     // 发送 application/x-www-form-urlencoded 类型的 POST 请求 (取消注释以使用)
            //     // this.result = await post(url, data, 'form');
            // } catch (error) {
            //     console.error('请求失败:', error);
            // }

        }
    },
    setup() {
        // const upload = ref();
        // const handleExceed = (files) => {
        //     console.log('yes', upload.value)
        //     if (upload.value) {
        //         console.log("files: " + files)
        //         upload.value.clearFiles();
        //         const file = files[0];
        //         file.uid = genFileId(); // 确保已经定义了 genFileId() 函数
        //         upload.value.handleStart(file);
        //     }
        // };
       
        // return {
        //     handleExceed,
           
        // }
    }
};
</script>

<style scoped></style>


<!-- 

handleEdit() {
            
            axios.put(gconfig.constants.API_ORIGIN + "/books", this.formData).then((res) => {
                if (res.data.flag) {
                    // 1.关闭修改弹窗
                    this.dialogFormVisible4Edit = false;
                    this.$message.success("更新成功");
                } else {
                    this.$message.error("更新失败");
                }

            }).finally(() => {
                // 2.刷新
                this.getAll();
            })
        }, -->